package com.oodso.say.utils;

import android.app.Activity;

import org.json.JSONException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * 项目名称：Sosoliuda
 * 类描述：
 * 创建人：资拥
 * 创建时间：16/10/13 上午11:10
 * 修改人：资拥
 * 修改时间：16/10/13 上午11:10
 * 修改备注：
 */
public abstract class HttpSubscriber<T> extends Subscriber<T> implements MyProgressDialog.OnDialogCancel {
    private Activity context;
    private MyProgressDialog dialog;

    public HttpSubscriber(Activity context) {
        this.context = context;
        dialog = new MyProgressDialog(context, this);
    }

    public HttpSubscriber(Activity context, boolean isDismiss) {
        this.context = context;
        if (isDismiss)
            dialog = new MyProgressDialog(context, isDismiss);
        else
            dialog = new MyProgressDialog(context, this);
    }

    public HttpSubscriber() {

    }

    @Override
    public void onCompleted() {
        dismiss();
    }

    public void dismiss(){
        if (null != dialog)
            dialog.dismiss();
    }
    @Override
    public void onError(Throwable e) {
        dismiss();
        String msg;
        if (e instanceof HttpException) {
            msg = "网络连接出错";
        } else if (e instanceof JSONException) {
            msg = "数据解析出错";
        } else if ("请求取消".equals(e.getMessage())) {
            msg = "请求取消";
        }
    }

    @Override
    public void onStart() {
        if (null != dialog && !dialog.isShowing())
            dialog.show();
    }

    @Override
    public void setOnDialogCancel() {
        if (!this.isUnsubscribed()) {
            this.unsubscribe();
        }
    }
}
